package org.bjf.aop;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;
import org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 自定义参数解析器用以支持同一个参数支持application/json和application/x-www-form-urlencoded解析
 *
 * @author bjf
 */
@Slf4j
public class MultiPostMethodResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;
    private RequestResponseBodyMethodProcessor jsonProcessor;
    private ServletModelAttributeMethodProcessor formProcessor;

    @PostConstruct
    public void init(){
        List<HandlerMethodArgumentResolver> resolvers = handlerAdapter.getArgumentResolvers();
        for (HandlerMethodArgumentResolver resolver : resolvers) {
            if (jsonProcessor != null && formProcessor != null) {
                break;
            }
            if (resolver instanceof RequestResponseBodyMethodProcessor) {
                jsonProcessor = (RequestResponseBodyMethodProcessor)resolver;
                continue;
            }
            if (resolver instanceof ServletModelAttributeMethodProcessor) {
                formProcessor = (ServletModelAttributeMethodProcessor)resolver;
            }
        }
    }


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getMethod().isAnnotationPresent(MultiPostResolver.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String contentType = request.getContentType();
        log.debug("Content-Type:", contentType);
        if (MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(contentType)) {
            return jsonProcessor.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
        }
        return formProcessor.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
    }
}
